﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.IO;

namespace PTCapture.Support
{
    public static class Converters
    {
        /// <summary>
        /// Convert an image to a Base64 string.
        /// </summary>
        /// <param name="imagePath"></param>
        /// <returns></returns>
        public static string ImageToString(string imagePath)
        {
            if (imagePath == null)
            {
                throw new ArgumentNullException();
            }

            try
            {
                Image i = Image.FromFile(imagePath);

                if (i == null)
                {
                    throw new Exception("Could not load image.");
                }

                return ImageToString(i);
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// Convert an image to a Base64 string.
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        public static string ImageToString(Image image)
        {
            MemoryStream ms = new MemoryStream();
            image.Save(ms, image.RawFormat);

            byte[] array = ms.ToArray();

            return Convert.ToBase64String(array);
        }

        /// <summary>
        /// Convert a Base64 string to an image.
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        public static Image StringToImage(string image)
        {
            if (image == null)
            {
                throw new ArgumentNullException();
            }

            byte[] array = Convert.FromBase64String(image);

            Image i = Image.FromStream(new MemoryStream(array));

            return i;
        }
    }
}
